package com.jayanslow.lighting.server.dmx;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Serial {
	private SerialConnection sconn;
	public Serial() throws SerialException {
		sconn = new SerialConnection(this);
		connect();
		sendCommand("reset");
	}
	public void connect() throws SerialException {
		if (!sconn.isConnected()) sconn.initialize();
	}
	public void disconnect() {
		if (sconn.isConnected()) sconn.close();
	}
	public void sendString(String s) throws SerialException {
		if (!sconn.isConnected()) sconn.initialize();
		sconn.send(s);
	}
	public void sendCommand(String s) throws SerialException {
		sendString("c" + s.toUpperCase() + "c");
	}
	public void sendDMX(short chan, short val) throws OverflowException, SerialException {
		if (chan > 512 || chan < 1) throw new OverflowException("DMX Channel must be between 1 and 512");
		if (val > 255 || val < 0) throw new OverflowException("8-bit DMX Value must be between 0x00 and 0xFF");
//		System.out.println("SERIAL DMX " + chan + " VALUE " + val);
		if (!sconn.isConnected()) sconn.initialize();
		NumberFormat formatter = new DecimalFormat("000");
		String s = "d" + formatter.format(chan) + formatter.format(val);
		sconn.send(s);
	}
	public void recieveMessage(String s) {
		//TODO recieve message
	}
}